import json
from datetime import datetime

from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from booktest.models import BookInfo

"""
GET     /books/         提供所有记录
POST    /books/         新增一条记录
GET     /books/<pk>/    提供指定id的记录
PUT     /books/<pk>/    修改指定id的记录
DELETE  /books/<pk>/    删除指定id的记录

响应数据    JSON
"""
# 分析需求需要的是传参数和不传参数的,所以需要制定两个视图类来进行逻辑处理
class BookAPIView(View):
    def get(self, request, pk):
        """
        获取指定id的书籍
        :param request: 前端传递过来的请求上下文
        :param pk: 前端在url中传递的查询参数
        :return: json字符串
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 获取到了book参数,拼接返回数据
        book_dict = {
             'id': book.id,
             'btitle': book.btitle,
             'bread': book.bread,
             'bpub_date': book.bpub_date,
             'bcomment': book.bcomment,
             'is_delete': book.is_delete,
             'image': book.image.url if book.image else ''
        }
        return JsonResponse(book_dict)

    def put(self, request, pk):
        """
        修改取指定id的书籍
        :param request: 前端传递过来的请求上下文
        :param pk: 前端在url中传递的查询参数
        :return: json字符串
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        book.btitle = json_dict['btitle']
        book.save()

        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bread': book.bread,
            'bpub_date': book.bpub_date,
            'bcomment': book.bcomment,
            'is_delete': book.is_delete,
            'image': book.image.url if book.image else ''
        }
        return JsonResponse(book_dict)


    def delete(self, request, pk):
        """
        删除取指定id的书籍
        :param request: 前端传递过来的请求上下文
        :param pk: 前端在url中传递的查询参数
        :return: json字符串
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        book.delete()
        return HttpResponse(status=204)




class BooksAPIView(View):

    def get(self, request):
        # 不需要获取数据
        # 获取所有记录
        # 返回json格式数据
        books = BookInfo.objects.all()
        # 构造json格式数据
        book_dict_list = []
        for book in books:
            book_dict_list.append(
                {'id': book.id,
                 'btitle': book.btitle,
                 'bread': book.bread,
                 'bpub_date': book.bpub_date,
                 'bcomment': book.bcomment,
                 'is_delete': book.is_delete,
                 'image': book.image
                 }
            )
        book_dict = {
            'books': book_dict_list
        }
        # return JsonResponse(book_dict_list,safe=False)
        return JsonResponse(book_dict)


    def post(self, request):
        """
        获取参数校验参数处理逻辑返回结果
        :param request: body原始数据
        :return:
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        # 同步到数据库
        book = BookInfo.objects.create(
            btitle=json_dict.get('btitle'),
            bcomment=json_dict.get('bcomment'),
            bread=json_dict.get('bread'),
            bpub_date=datetime.strptime(json_dict.get('bpub_date'), '%Y-%m-%d').date()

        )
        response_book_dict = {
             'id': book.id,
             'btitle': book.btitle,
             'bread': book.bread,
             'bpub_date': book.bpub_date,
             'bcomment': book.bcomment,
             'is_delete': book.is_delete,
             'image': book.image.url if book.image else ''
        }
        return JsonResponse(response_book_dict)
